package com.robot.common.api;

import com.robot.common.enums.ResponseEnum;
import com.robot.common.exception.BusinessException;
import com.robot.common.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
@Component
public class CurrentUserSupport {

    //根据token获取当前用户的userId
    public Long getCurrentUserId() {
        // SpringBoot提供的抓取前端请求的方法
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");
        //TODO:Bearer添加校验
        boolean verifyRes = JwtTokenUtil.verify(token);
        String idStr = JwtTokenUtil.getUserIdFromToken(token);
        if (!verifyRes||StringUtils.isBlank(idStr)) {
            throw new BusinessException(ResponseEnum.JWT_LOSE_EFFECT.getCode(), "未获取到用户Id");
        }
        Long id = Long.valueOf(idStr);
        return id;
    }



}
